package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.core.util.PageUtil;
import com.hbnu.system.mapper.ConstructionMapper;
import com.hbnu.system.model.dto.CheckBackDTO;
import com.hbnu.system.model.dto.SearchPageDTO;
import com.hbnu.system.model.dto.UserDTO;
import com.hbnu.system.model.entity.Audit;
import com.hbnu.system.model.entity.Construction;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.model.vo.InfoVO;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-05-16
 */
@Service
public class ConstructionServiceImpl extends ServiceImpl<ConstructionMapper, Construction> implements IConstructionService {

    @Autowired private IConstructionService iConstructionService;

    @Autowired private IUserService iUserService;

    @Autowired private IDeptService iDeptService;
    @Autowired
    IAuthorityService iAuthorityService;
    @Autowired
    AuditService auditService;
    @Override
    public boolean addConstruction(Construction construction) {
        if(StrUtil.isEmpty(construction.getClassifi()) || StrUtil.isBlank(construction.getClassifi())){
            throw new BaseException("请输入统计分类!");
        }

        if(StrUtil.isEmpty(construction.getProjectName()) || StrUtil.isBlank(construction.getProjectName())){
            throw new BaseException("请输入项目名称!");
        }

        Construction one = super.getOne(Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getProjectName, construction.getProjectName()));
        if(Objects.nonNull(one)){
            throw new BaseException("该名称已被使用!");
        }

        if(StrUtil.isEmpty(construction.getDisciplineType()) || StrUtil.isBlank(construction.getDisciplineType())){
            throw new BaseException("请输入学科类型!");
        }

//        if(StrUtil.isEmpty(knowLeage.getAnnex().toString()) || StrUtil.isBlank(knowLeage.getAnnex().toString())){
//            throw new BaseException("请选择附件");
//        }

        LocalDate nowDate = LocalDate.now();

        if(StrUtil.isEmpty(construction.getApprovalYear()) || StrUtil.isBlank(construction.getApprovalYear())){
            throw new BaseException("请输入批准年度");
        }
        String substring = nowDate.toString().substring(0, 4);
        if(Integer.parseInt(construction.getApprovalYear()) > Integer.parseInt(substring)){
            throw new BaseException("批准年度有误!");
        }

        construction.setStatus("草稿");
        if(Objects.isNull(construction.getEnteredDate())) {
            construction.setEnteredDate(LocalDate.now());
        }
        return baseMapper.insert(construction) == 1;
    }

    @Override
    public boolean deleteConstruction(String constructionID) {
        Construction construction = super.getOne(Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getConstructionID, constructionID));
        if(Objects.isNull(construction)){
            throw new BaseException("学科建设编号有误");
        }
        return baseMapper.deleteById(construction) == 1;
    }

    @Override
    public boolean updateConstruction(Construction construction) {

        Construction one1 = super.getOne(Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getConstructionID, construction.getConstructionID()));
        if (Objects.isNull(one1)){
            throw new BaseException("学科建设编号有误");
        }

        String status = construction.getStatus();
        if (status.equals("待校级审核")){
            throw new BaseException("审核中不可修改!");
        }

        if(StrUtil.isEmpty(construction.getClassifi()) || StrUtil.isBlank(construction.getClassifi())){
            throw new BaseException("请输入统计分类!");
        }

        if(StrUtil.isEmpty(construction.getProjectName()) || StrUtil.isBlank(construction.getProjectName())){
            throw new BaseException("请输入项目名称!");
        }

        Construction one = super.getOne(Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getProjectName, construction.getProjectName()));
        if(Objects.nonNull(one) && !one.getConstructionID().equals(construction.getConstructionID())){
            throw new BaseException("该名称已被使用!");
        }

        if(StrUtil.isEmpty(construction.getDisciplineType()) || StrUtil.isBlank(construction.getDisciplineType())){
            throw new BaseException("请输入学科类型!");
        }

//        if(StrUtil.isEmpty(knowLeage.getAnnex().toString()) || StrUtil.isBlank(knowLeage.getAnnex().toString())){
//            throw new BaseException("请选择附件");
//        }

        LocalDate nowDate = LocalDate.now();

        if(StrUtil.isEmpty(construction.getApprovalYear()) || StrUtil.isBlank(construction.getApprovalYear())){
            throw new BaseException("请输入批准年度");
        }
        String substring = nowDate.toString().substring(0, 4);
        if(Integer.parseInt(construction.getApprovalYear()) > Integer.parseInt(substring)){
            throw new BaseException("批准年度有误!");
        }
//
//        construction.setEnteredDate(nowDate);
//        construction.setStatus("草稿");

        return baseMapper.updateById(construction) == 1;
    }

    @Override
    public Construction getConstruction(String constructionID) {
        Construction construction = super.getOne(Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getConstructionID, constructionID));
        if(Objects.isNull(construction)){
            throw new BaseException("学科建设编号异常!未查找到该学科建设");
        }
        return construction;
    }

    @Override
    public IPage<Construction> pageCondition(SearchPageDTO searchPageDTO) {
        IPage<Construction> page = PageUtil.getPage(searchPageDTO.getPageNum(), searchPageDTO.getPageSize());
        LambdaQueryWrapper<Construction> wrapper = Wrappers.lambdaQuery(Construction.class);
        IPage<Construction> constructionIPage = baseMapper.selectPage(page, wrapper);

        List<Construction> records = constructionIPage.getRecords();
        List<Construction> ConstructionS = new ArrayList<>();

        int count = 1;
        int start = searchPageDTO.getPageSize() * (searchPageDTO.getPageNum()-1)+1;
        int end = searchPageDTO.getPageNum() * searchPageDTO.getPageSize();
        Collections.reverse(records);
        for (Construction record:records) {
            if (count >= start && count <= end){
                ConstructionS.add(this.getConstruction(record.getConstructionID()));
            }
            count += 1;
        }

//        Collections.reverse(ConstructionS);
        constructionIPage.setRecords(ConstructionS);
        constructionIPage.setTotal(records.size());
        return constructionIPage;
    }

    @Override
    public Boolean schoolCheckPass(String token,String constructionID) {
        Construction construction = iConstructionService.getConstruction(constructionID);
        if (Objects.isNull(construction)){
            throw new BaseException("该学科建设编号有误!");
        }
        if(!construction.getStatus().equals("待校级审核")){
            throw new BaseException("该学科建设状态不处于该环节!");
        }
        construction.setStatus("审核通过");
        construction.setReason("");

        InfoVO info = JwtUtils.getInfo(token);
        String[] strings = new String[1];
        strings[0] = iAuthorityService.getById(info.getRoles()[0]).getText();
        User user = iUserService.getById(info.getUid());
        String role = strings[0];
        String name = user.getName();

        Audit audit = new Audit();
        audit.setSynthesisID(constructionID);
        audit.setAuditerRole(role);
        audit.setAuditerName(name);
        audit.setStatusChange("学科建设待校级审核->校级审核通过");
        audit.setAuditOpinion("通过");
        audit.setAuditerTime(LocalDateTime.now());
        auditService.addAudit(audit);
        return baseMapper.updateById(construction) == 1;
    }

    @Override
    public Boolean schoolCheckBack(String token,CheckBackDTO checkBackDTO) {
        String id = checkBackDTO.getID();
        Construction construction = iConstructionService.getConstruction(id);
        if (Objects.isNull(construction)){
            throw new BaseException("该学科建设编号有误!");
        }
        if(!construction.getStatus().equals("待校级审核")){
            throw new BaseException("该学科建设状态不处于该环节!");
        }
        construction.setStatus("被校级退回");
        construction.setReason(checkBackDTO.getReason());

        InfoVO info = JwtUtils.getInfo(token);
        String[] strings = new String[1];
        strings[0] = iAuthorityService.getById(info.getRoles()[0]).getText();
        User user = iUserService.getById(info.getUid());
        String role = strings[0];
        String name = user.getName();

        Audit audit = new Audit();
        audit.setSynthesisID(checkBackDTO.getID());
        audit.setAuditOpinion(checkBackDTO.getReason());
        audit.setAuditerRole(role);
        audit.setAuditerName(name);
        audit.setStatusChange("学科建设待校级审核->被校级退回");
        auditService.addAudit(audit);
        return baseMapper.updateById(construction) == 1;
    }

    @Override
    public IPage<Construction> userGetRelateConstruction(UserDTO userDTO) {
        if(Objects.isNull(iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getName,userDTO.getName())))){
            throw new BaseException("用户姓名有误!");
        }
        IPage<Construction> page = PageUtil.getPage(userDTO.getPageNum(), userDTO.getPageSize());
        LambdaQueryWrapper<Construction> wrapper = Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getEntered, userDTO.getName())
                .or().like(Construction::getHead, userDTO.getName());
        IPage<Construction> constructionIPage = baseMapper.selectPage(page, wrapper);
        List<Construction> records = constructionIPage.getRecords();
//        IPage<PaperVO> paperVOIPage = iBeanService.copyPageProperties(paperIPage, PaperVO.class);
        ArrayList<Construction> constructionList = new ArrayList<>();

        //对分页的设置
        int count = 1;
        int start = userDTO.getPageSize() * (userDTO.getPageNum()-1)+1;
        int end = userDTO.getPageNum() * userDTO.getPageSize();
        Collections.reverse(records);
        for (Construction record:records) {
            if (count >= start && count <= end){
                constructionList.add(this.getConstruction(record.getConstructionID()));
//                paperList.add(this.getPaperVO(record.getPaperID()));
            }
            count += 1;
        }

//        Collections.reverse(constructionList);
        constructionIPage.setRecords(constructionList);
        constructionIPage.setTotal(records.size());

        return constructionIPage;
    }

    @Override
    public IPage<Construction> schoolUserGetConstruction(UserDTO userDTO) {
        User one = iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getName, userDTO.getName()));
        if(Objects.isNull(one)){
            throw new BaseException("用户姓名有误!");
        }
//        String dept = one.getDept();
//        String deptName = iDeptService.getById(dept).getDeptName();
        String role = one.getRole();
        if(!role.equals("19190251173")){
            throw new BaseException("该用户权限不为校级审核员!");
        }
        IPage<Construction> page = PageUtil.getPage(userDTO.getPageNum(), userDTO.getPageSize());
        LambdaQueryWrapper<Construction> wrapper = Wrappers.lambdaQuery(Construction.class)
//                .eq(Paper::getDept,deptName)
                .and(wrapper1 -> wrapper1.eq(Construction::getStatus,"待校级审核"));

        IPage<Construction> constructionIPage = baseMapper.selectPage(page, wrapper);
        List<Construction> records = constructionIPage.getRecords();
//        IPage<PaperVO> paperVOIPage = iBeanService.copyPageProperties(paperIPage, PaperVO.class);
        ArrayList<Construction> constructionList = new ArrayList<>();

        //对分页的设置
        int count = 1;
        int start = userDTO.getPageSize() * (userDTO.getPageNum()-1)+1;
        int end = userDTO.getPageNum() * userDTO.getPageSize();
        Collections.reverse(records);
        for (Construction record:records) {
            if (count >= start && count <= end){
//                this.getPaper(record.getPaperID())
                constructionList.add(this.getConstruction(record.getConstructionID()));
            }
            count += 1;
        }

//        Collections.reverse(constructionList);
        constructionIPage.setRecords(constructionList);
        constructionIPage.setTotal(records.size());

        return constructionIPage;
    }

    @Override
    public Boolean CommitConstruction(String constructionID) {
        Construction construction = super.getOne(Wrappers.lambdaQuery(Construction.class)
                .eq(Construction::getConstructionID, constructionID));
        if(!construction.getStatus().equals("草稿") && !construction.getStatus().equals("被校级退回")){
            throw new BaseException("该学科建设不适用于该阶段!");
        }

        if(StrUtil.isBlank(construction.getClassifi()) || StrUtil.isEmpty(construction.getClassifi())){
            throw new BaseException("请输入统计分类!");
        }
        if(StrUtil.isBlank(construction.getProjectName()) || StrUtil.isEmpty(construction.getProjectName())){
            throw new BaseException("请输入项目名称!");
        }
        if(StrUtil.isBlank(construction.getDisciplineType()) || StrUtil.isEmpty(construction.getDisciplineType())){
            throw new BaseException("请输入学科类型!");
        }
        if(StrUtil.isBlank(construction.getApprovalYear()) || StrUtil.isEmpty(construction.getApprovalYear())){
            throw new BaseException("请输入批准年度!");
        }
        if(StrUtil.isBlank(construction.getApprovalBatch()) || StrUtil.isEmpty(construction.getApprovalBatch())){
            throw new BaseException("请输入批准批次!");
        }
        if(StrUtil.isBlank(construction.getEntered()) || StrUtil.isEmpty(construction.getEntered())){
            throw new BaseException("请输入录入人!");
        }

        construction.setStatus("待校级审核");
        construction.setReason("");

        return baseMapper.updateById(construction) == 1;
    }
}
